################################################################################
# Name   : Makefile
# Date   : 01-13-2015
# Author : Sylvain Nieuwlandt -- nicholas.rush.developper@gmail.com
################################################################################

# PROJECT SETTINGS #############################################################
PROJECT_NAME=nr1
EXE_NAME=ExcusePetit
VERSION=0.0.1_SNAPSHOT
BIN_DIR=bin/
SRC_DIR=src/
INC_DIR=includes/
TEST_DIR=test/
SRC_EXT=cc
MAIN_FILE=ep21

# COMPILATION SETTINGS #########################################################
CC=g++
CFLAGS=-pedantic -Wall -Werror -Wextra -Wshadow -c -I$(INC_DIR) 
CFLAGS+=-D_XOPEN_SOURCE=500
LDFLAGS=-Wall -Werror
DEBUG_CFLAGS=-g -pg
DEBUG_LDFLAGS=-g

# COMPILATION MAGIC ############################################################
define toObjectFile 
$(BIN_DIR)$(basename $(notdir $1)).o
endef

define debugBuild 
	$(CC) $(CFLAGS) $(DEBUG_CFLAGS) $1 -o $(call toObjectFile,$1)
endef

define releaseBuild 
	$(CC) $(CFLAGS) $1 -o $(call toObjectFile,$1)
endef


SOURCES = $(shell for src in `find $(SRC_DIR) -name "*.$(SRC_EXT)"`; do echo $$src; done)
DEBUG_FINAL=$(PROJECT_NAME)_$(VERSION)_debug
RELEASE_FINAL=$(EXE_NAME)_$(VERSION)
OBJS_DEBUG=$(foreach source, $(SOURCES), $(call toObjectFile,$(source)))
TEST_SOURCES=$(shell for src in `find $(TEST_DIR) -name "*.$(SRC_EXT)"`; do echo $$src; done)

.PHONY: clean mrproper all debug test

all : debug

clean:
	rm -rf *~
	rm -f $(BIN_DIR)*

mrproper: clean
	rm -f $(DEBUG_FINAL)
	rm -f $(RELEASE_FINAL)
	rm -f $(PROJECT_NAME)_tests

debug: $(DEBUG_FINAL)

test: $(OBJS_DEBUG)
	cp $(BIN_DIR)*.o $(TEST_DIR)
	$(CC) $(CFLAGS) $(DEBUG_CFLAGS) $(TEST_DIR)*.cc
	mv $(TEST_DIR)*.o .
	rm -f $(MAIN_FILE).o
	$(CC) -o $(PROJECT_NAME)_tests ./*.o
	rm -f ./*.o

$(DEBUG_FINAL): $(OBJS_DEBUG)
	$(CC) $(LDFLAGS) $(DEBUG_LDFLAGS) $^ -o $(DEBUG_FINAL)

$(OBJS_DEBUG): $(SOURCES)
	$(foreach source, $(SOURCES), $(shell $(call debugBuild,$(source))))
